<template>
	<el-dialog :title="isEdit ? '编辑问答' : '新增问答'" :visible.sync="dialogVisible" width="60%" :before-close="handleClose" :close-on-click-modal="false" :close-on-press-escape="false">
		<el-form label-position="left" label-width="100px" :model="form" :rules="rules" ref="form" class="create-question-form">
			<el-form-item label="分类">
				<el-cascader v-model="form.catagory" :options="options" @change="handleChange" style="width: 100%;"></el-cascader>
			</el-form-item>
			<el-form-item label="问题" prop="question">
				<el-input v-model="form.question" placeholder="请输入问题" maxlength="250"></el-input>
			</el-form-item>
			<el-form-item label="答案类型">
				<el-radio-group v-model="form.answerType" @input="handleTypeChange">
					<el-radio label="text">{{ answerTypeText['text'] }}</el-radio>
					<el-radio label="image">{{ answerTypeText['image'] }}</el-radio>
					<el-radio label="video">{{ answerTypeText['video'] }}</el-radio>
					<el-radio label="pdf">{{ answerTypeText['pdf'] }}</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item v-if="form.answerType === 'text'" label="回答" prop="answer">
				<el-input type="textarea" placeholder="请输入回复内容" v-model="form.answer" maxlength="2000" show-word-limit resize="none"> </el-input>
			</el-form-item>
			<el-form-item v-if="form.answerType === 'video'" label="回答" prop="resouceUrl">
				<el-button type="primary" onclick="document.getElementById('video_file_input').click()" v-loading.fullscreen.lock="fullscreenLoading">上传视频文件</el-button>
				<input style="display: none" type="file" name="file" id="video_file_input" value="" accept=".mp4, .mov" @change="beforeUpload" />
				<p v-if="form.resouce.length > 0">{{ form.resouce[0].name }}</p>
			</el-form-item>
			<el-form-item v-if="form.answerType === 'pdf'" label="回答" class="upload-file" prop="resouceUrl">
				<el-button type="primary" onclick="document.getElementById('pdf_file_input').click()" v-loading.fullscreen.lock="fullscreenLoading">上传pdf文件</el-button>
				<input style="display: none" type="file" name="file" id="pdf_file_input" value="" accept="application/pdf" @change="beforeUpload" />
				<p v-if="form.resouce.length > 0">{{ form.resouce[0].name }}</p>
			</el-form-item>
			<el-form-item v-if="form.answerType === 'image'" label="回答" class="upload-file" prop="resouceUrl">
				<el-button type="primary" onclick="document.getElementById('image_file_input').click()" v-loading.fullscreen.lock="fullscreenLoading">上传图片文件</el-button>
				<input style="display: none" type="file" name="file" id="image_file_input" value="" accept="image/gif,image/jpg,image/jpeg,image/png,image/webp" @change="beforeUpload" />
				<p v-if="form.resouce.length > 0">{{ form.resouce[0].name }}</p>
			</el-form-item>
			<!-- <el-form-item label="仅供内部用户使用" label-width="150px">
				<el-switch v-model="form.isPrivate"></el-switch>
			</el-form-item> -->
		</el-form>
		<span slot="footer" class="dialog-footer">
			<el-button @click="handleClose">取消</el-button>
			<el-button type="primary" @click="handleConfirm">确定</el-button>
		</span>
	</el-dialog>
</template>
<script>
import { forceBtnBlur, fixUploadPercent, transformData, extractIds } from '@/utils/MyVueUtil.js';
import { getUploadFileConfig, getKnowledgeBaseCategoryParent } from '@/api/api';
import { uploadFile } from '@/utils/tool.js';
export default {
	props: {
		visible: {
			type: Boolean,
			default: false
		},
		question: {
			type: Object,
			default: () => ({})
		},
		groupList: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			dialogVisible: false,
			form: {
				catagory: [],
				question: '',
				answer: '',
				isPrivate: false,
				answerType: 'text', // 文本 text | PDF pdf | 图片 image | 视频 video
				resouce: [],
				resouceUrl: '' // 资源链接
			},
			answerTypeText: {
				text: '文本',
				pdf: 'PDF',
				image: '图片',
				video: '视频'
			},
			uploadFileConfig: getUploadFileConfig(),
			fullscreenLoading: false,
			isEdit: false,
			resouceBackup: {},
			options: [],
			rules: {
				question: [{ required: true, message: '请输入问题', trigger: ['blur', 'input'] }],
				answer: [{ required: true, message: '请输入回复内容', trigger: ['blur', 'input'] }],
				resouceUrl: [{ required: true, message: '请上传文件', trigger: ['blur', 'input'] }]
			}
		};
	},
	watch: {
		groupList: {
			handler(val) {
				this.options = transformData(this.groupList.slice(2));
			},
			deep: true
		},
	},
	mounted() {
		this.dialogVisible = this.visible;
		console.log('question', this.question);
		if (this.question.id) {
			const { fileName, answer, type, name } = this.question;
			this.isEdit = true;
			this.form.question = name;
			this.form.answer = answer;
			this.form.answerType = type || 'text';
			if (type !== 'text') {
				this.form.resouce = [{ name: fileName, url: answer, type, size: 0 }];
				this.form.resouceUrl = answer;
			}
			this.form.isPrivate = !this.question.isPublic;
			this.getCategoryList(this.question.categoryId);
		}

		this.options = transformData(this.groupList.slice(2));
		console.log('options', this.options);
		
	},
	methods: {
		// 关闭
		handleClose() {
			this.dialogVisible = false;
			this.$emit('close');
		},
		// 新增问题
		handleConfirm() {
			console.log(this.form);
			this.$refs.form.validate(valid => {
				if (valid) {
					// this.dialogVisible = false;
					this.$emit('confirm', this.form);
				}
			});
		},
		// 上传资源前处理
		async beforeUpload(event) {
			const file = event.target.files[0]; // 获取单个文件
			if (this.form.answerType === 'pdf' && (file.size > pdfMaxSize)) {
				const size = Math.floor(pdfMaxSize / 1024 / 1024);
				this.$message.error(`请上传小于${size}M的文件！`);
				return false;
			}

			if (['video', 'image'].includes(this.form.answerType) && (file.size > videoMaxSize)) {
				const size = Math.floor(videoMaxSize / 1024 / 1024);
				this.$message.error(`请上传小于${size}M的文件！`);
				return false;
			}
			if (this.form.answerType === 'video') {
				const isVideo = file.type === 'video/mp4' || file.type === 'video/quicktime';
				if (!isVideo) {
					this.$message.error('上传失败，仅支持上传.mp4/.mov格式的视频文件！');
					return false;
				}
			}
			if (this.form.answerType === 'pdf') {
				const isPdf = file.type === 'application/pdf';
				if (!isPdf) {
					this.$message.error('上传失败，仅支持上传.pdf格式的文件！');
					return false;
				}
			}
			if (this.form.answerType === 'image') {
				// image/gif,image/jpg,image/jpeg,image/png,image/webp
				const isImage = ['image/gif', 'image/jpg', 'image/jpeg', 'image/png', 'image/webp'].includes(file.type);
				if (!isImage) {
					this.$message.error('上传失败，仅支持上传.png/.jpg格式的图片文件！');
					return false;
				}
			}
			this.fullscreenLoading = true;
			try {
				let data = await uploadFile(file);
				console.log('uploadFile', data);
				const { name, size, url } = data;
				const resouce = {
					url: url,
					name: name,
					size: size,
					type: this.form.answerType
				};
				this.form.resouce = [resouce];
				this.form.resouceUrl = url;
				this.form.answer = this.form.resouceUrl;
				this.$refs.form.clearValidate(['resouceUrl']);
			} catch (error) {
				console.error('uploadFile error:', error);
				if (error.code === 'ECONNABORTED') {
					this.$message.error('上传超时！');
				} else {
					this.$message.error('上传失败！');
				}
			} finally {
				this.fullscreenLoading = false;
			}
		},
		// 文件选择后处理
		handleTypeChange(value) {
			console.log('handleTypeChange', value, this.form.answerType);
			if (this.form.resouce?.length > 0) {
				this.resouceBackup[this.form.resouce[0].type] = [...this.form.resouce];
			}
			this.form.resouce = this.resouceBackup[value] || [];
			this.form.answer = '';
			this.form.resouceUrl = this.form.resouce[0]?.url || '';
			this.form.answer = this.form.resouceUrl;
			this.$refs.form.clearValidate(['resouceUrl']);
			this.$refs.form.clearValidate(['answer']);
			this.$refs.uploadComponent?.clearFiles();
		},
		// 获取分类路径
		getCategoryList(id) {
			if (!id) return;
			getKnowledgeBaseCategoryParent(id)
				.then(res => {
					console.log(res.data.data);
					const data = extractIds(res.data.data);
					console.log('getCategoryList', data);
					
					this.form.catagory = data;
				})
				.catch(err => {
					console.log(err);
				});
		},
	}
};
</script>
<style lang="less">
.create-question-form .el-form-item .el-form-item__content .el-textarea {
	height: 200px;
}
.create-question-form .el-form-item .el-form-item__content .el-textarea .el-textarea__inner {
	height: 100%;
}
</style>
